<template>
  <div class="flex gap-2">
    <el-tag v-for="tag in tags" :key="tag" :disable-transitions="false">
      {{ tag }}
    </el-tag>
    <el-tag v-for="tag in appendTags" :key="tag" :disable-transitions="false">
      {{ tag }}
    </el-tag>
    <el-input
      v-if="inputVisible"
      ref="InputRef"
      v-model="inputValue"
      class="w-20"
      size="small"
      @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm"
    />
    <el-button v-else class="button-new-tag" size="small" @click="showInput"> + New Tag </el-button>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, ref, onMounted, onUpdated } from 'vue'
import { ElInput } from 'element-plus'
import { get, post } from '@/util/request.js'

const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

// 自动添加tag的间隔
const setTagInterval = 5000
let settingTag = false
// 根据内容自动探测的tag
let tags = ref([])
// 新添加的tag
let appendTags = []
// 服务器里已经存在的tag
let remoteTags = []

const props = defineProps({
  content: { type: String }
})
const emits = defineEmits(['handle'])

onMounted(() => {
  getData()
})

onUpdated(() => {
  // 不要实时更新
  if (settingTag) {
    return
  }
  settingTag = true
  setTimeout(() => {
    settingTag = false
  }, setTagInterval)

  let tt = []
  for (let item of remoteTags) {
    if (props['content'].indexOf(item.title) > -1) {
      tt.push(item.title)
    }
  }
  tags.value = tt
  pushTags()
})

const getData = () => {
  get('/tag/get').then((resp) => {
    remoteTags = resp.insts
  })
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    appendTags.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
  pushTags()
}

const pushTags = () => {
  const total = appendTags.concat(tags.value)
  emits('handle', total)
}
</script>
